﻿/**
 *@description:
 *@file: transformations.cpp
 *@author: snow-tyan
 *@email: zziywang@163.com
 *@date: 2023-01-17 14:18:44
 *@copyright: 2018-2022 AiRiA. All rights reserved.
 */

#include "mygl/es_image.h"
#include "mygl/shader.h"
#include "mygl/util.h"

#include <cmath>
#include <iostream>
#include <memory>

#include <glad/glad.h>   // 管理OpenGL的函数指针
#include <GLFW/glfw3.h>  // 提供窗口和OpenGL context

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#ifndef PROJECT_ROOT
#define PROJECT_ROOT "/home/snow/OpenGLESProjects/MyOpenGLES_glfw"
#endif

using namespace mygl;

const std::string kProjectRoot = PROJECT_ROOT + std::string("/");
const std::string kWorkSpaceRoot = kProjectRoot + "01-GettingStarted/04-Transform/";
const std::string kShaderRoot = kWorkSpaceRoot + "transformations/";
const std::string kResourcesRoot = kProjectRoot + "resources/textures/";
constexpr const unsigned int kWindowWidth = 800;
constexpr const unsigned int kWindowHeight = 600;
constexpr const char *kWindowName = "Transformations";

void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *window);

std::shared_ptr<Shader> ShaderInit() {
  std::string vertex_path = kShaderRoot + "shader.vs";
  std::string fragment_path = kShaderRoot + "shader.fs";
  auto shader = std::make_shared<Shader>(vertex_path, fragment_path);
  CHECK_MSG(shader->Init() == 0, "Shader Init Failed");
  return shader;
}

std::shared_ptr<EsImage> LoadImage(const std::string &pic_name) {
  std::string picture = kResourcesRoot + pic_name;
  std::cout << picture << std::endl;
  auto es_image = std::make_shared<EsImage>();
  CHECK_MSG(es_image->LoadImage(picture) == 0, "Load Image Failed");
  es_image->PrintLoadTime();
  es_image->PrintImageInfo();
  return es_image;
}

void PrintGlmVector(const glm::vec3 &vec) {
  printf("vec(%.1f, %.1f, %.1f)\n", vec.x, vec.y, vec.z);
}

glm::mat4 TransformTest() {
  glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);  // x轴的单位向量，仅用于测试
  PrintGlmVector(vec);
  glm::mat4 trans(1.0f);  // 初始化默认是零矩阵
  trans = glm::translate(trans, glm::vec3(0.1f, 0.1f, 0.1f));  // 位移
  PrintGlmVector(trans * vec);
  trans = glm::rotate(trans, glm::radians(90.0f),
                      glm::vec3(0.0f, 0.0f, 1.0f));  // 沿z轴逆时针旋转90度
  PrintGlmVector(trans * vec);
  trans = glm::scale(trans, glm::vec3(0.5f, 0.5f, 1.0f));  // 缩放
  PrintGlmVector(trans * vec);
  return trans;
}

int main() {
  // glfw: initialize and configure
  // ------------------------------
  glfwInit();
  // OpenGL 3.3
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 核心模式

  // glfw window creation
  // --------------------
  GLFWwindow *window =
      glfwCreateWindow(kWindowWidth, kWindowHeight, kWindowName, NULL, NULL);
  if (window == NULL) {
    std::cout << "Failed to create GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }
  glfwMakeContextCurrent(window);
  glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

  // glad: load all OpenGL function pointers
  // ---------------------------------------
  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    std::cout << "Failed to initialize GLAD" << std::endl;
    return -1;
  }
  // print: gl info
  printf("GL_VENDOR: %s\n", glGetString(GL_VENDOR));  // 打印gl供应商
  printf("GL_VERSION: %s\n", glGetString(GL_VERSION));  // 打印gl版本，确定使用gles3
  // printf("%s\n", glGetString(GL_EXTENSIONS));  // 打印GL_EXTENSIONS
  int max_attributes;
  glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_attributes);  // 硬件支持的最大顶点属性数量
  printf("Max number of vertex attribute supported: %d\n", max_attributes);

  // build and compile our shader zprogram
  // ------------------------------------
  auto shader = ShaderInit();

  // set up vertex data (and buffer(s)) and configure vertex attributes
  // ------------------------------------------------------------------
  GLfloat vertices[] = {
      // positions          // colors       // texture coords
      0.5f,  0.5f,  0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,  // top right
      0.5f,  -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,  // bottom right
      -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,  // bottom left
      -0.5f, 0.5f,  0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f   // top left
  };
  GLshort indices[] = {
      0, 1, 3,  // first triangle
      1, 2, 3   // second triangle
  };
  GLuint vao, vbo, ebo;
  glGenVertexArrays(1, &vao);
  glGenBuffers(1, &vbo);
  glGenBuffers(1, &ebo);

  glBindVertexArray(vao);

  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

  // position attribute
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void *)0);
  glEnableVertexAttribArray(0);
  // color attribute
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat),
                        (void *)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  // texture coord attribute
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat),
                        (void *)(6 * sizeof(GLfloat)));
  glEnableVertexAttribArray(2);

  // load and create a texture
  // -------------------------
  GLuint texture1, texture2;
  // texture 1
  // ---------
  glGenTextures(1, &texture1);
  glBindTexture(GL_TEXTURE_2D, texture1);
  // set the texture wrapping parameters
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  // set texture filtering parameters
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  // load image, create texture and generate mipmaps
  auto es_image = LoadImage("container.jpg");
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, es_image->width, es_image->height, 0, GL_RGB,
               GL_UNSIGNED_BYTE, es_image->data);
  glGenerateMipmap(GL_TEXTURE_2D);

  // texture 2
  // ---------
  glGenTextures(1, &texture2);
  glBindTexture(GL_TEXTURE_2D, texture2);
  // set the texture wrapping parameters
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  // set texture filtering parameters
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  // load image, create texture and generate mipmaps
  auto es_image2 = LoadImage("awesomeface.png");
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, es_image2->width, es_image2->height, 0, GL_RGBA,
               GL_UNSIGNED_BYTE, es_image2->data);  // 注意它是4通道RGBA
  glGenerateMipmap(GL_TEXTURE_2D);

  // tell opengl for each sampler to which texture unit it belongs to (only has to be
  // done once)
  // -------------------------------------------------------------------------------------------
  shader->UseProgram();
  shader->SetUniformInt("pic_texture", 0);
  shader->SetUniformInt("pic2_texture", 1);
  // glm::mat4 transform = TransformTest();
  // shader->SetUniformMat4Float("transform", glm::value_ptr(transform));
  // render loop
  // -----------
  while (!glfwWindowShouldClose(window)) {
    // input
    // -----
    processInput(window);

    // render
    // ------
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    // bind textures on corresponding texture units
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture1);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, texture2);

    // transform
    // 声明顺序是先位移、再旋转、最后缩放
    // 实际执行是先缩放、再旋转、最后位移
    // 因为矩阵*向量是右结合
    glm::mat4 trans(1.0f);
    trans = glm::translate(trans, glm::vec3(0.5f, 0.5f, 0.0f));
    trans = glm::rotate(trans, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f));
    trans = glm::scale(trans, glm::vec3(0.60f, 0.60f, 1.0f));

    shader->UseProgram();
    shader->SetUniformMat4Float("transform", trans);

    // render container
    glBindVertexArray(vao);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);

    // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
    // -------------------------------------------------------------------------------
    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  // optional: de-allocate all resources once they've outlived their purpose:
  // ------------------------------------------------------------------------
  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteBuffers(1, &ebo);

  // glfw: terminate, clearing all previously allocated GLFW resources.
  // ------------------------------------------------------------------
  glfwTerminate();
  return 0;
}

// process all input: query GLFW whether relevant keys are pressed/released this frame
// and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window) {
  if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
    glfwSetWindowShouldClose(window, true);
  }
}
// glfw: whenever the window size changed (by OS or user resize) this callback function
// executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow *window, int width, int height) {
  // make sure the viewport matches the new window dimensions; note that width and
  // height will be significantly larger than specified on retina displays.
  glViewport(0, 0, width, height);
}
